package com.cmas.platform.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.aidex.common.annotation.DataSource;
import com.aidex.common.constant.Constants;
import com.aidex.common.enums.DataSourceType;
import com.aidex.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cmas.platform.common.annotation.OperatorDataScope;
import com.cmas.platform.domain.*;
import com.cmas.platform.domain.em.NotificationTypeEnum;
import com.cmas.platform.domain.em.SystemNotificationTypeEnum;
import com.cmas.platform.mapper.*;
import com.cmas.platform.service.UserRecordService;
import com.cmas.platform.vo.RegionVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aidex.common.core.domain.BaseEntity;
import com.aidex.common.utils.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.platform.service.RegionService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 地区表Service业务层处理
 *
 * @author su
 * @email 1218819874@qq.com
 * @date 2023-03-14
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    private static final Logger log = LoggerFactory.getLogger(RegionServiceImpl.class);

    @Autowired
    private SectionMapper sectionMapper;
    @Autowired
    private RegionMapMapper regionMapMapper;
    @Autowired
    private ApproveRecordMapper approveRecordMapper;
    @Autowired
    private ApproveConfigMapper approveConfigMapper;
    @Autowired
    private PlatformConfigMapper platformConfigMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserRecordMapper userRecordMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 校验地区编码的唯一性
     *
     * @param region 地区
     */
    @Override
    public boolean checkCodeUnique(Region region) {
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();
        Region notEqual = baseMapper.selectOne(queryWrapper
                .lambda().eq(Region::getCode, region.getCode()));
        if (notEqual != null) {
            return !notEqual.getId().equals(region.getId());
        }
        return false;
    }

    @Override
    public RegionVo getRegionDetail(String id) {
        RegionVo regionVo = new RegionVo();
        regionVo.setRegion(baseMapper.selectById(id));
        regionVo.setSectionList(sectionMapper.selectList(new QueryWrapper<Section>().lambda()
                .eq(Section::getRegionId, id).or()
                .eq(Section::getType, "0")
                .orderByAsc(Section::getType)
                .orderByAsc(Section::getSort)));
        regionVo.setRegionMap(regionMapMapper.selectOne(new QueryWrapper<RegionMap>().lambda()
                .eq(RegionMap::getRegionId, id)));
        return regionVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void approve(ApproveRecord approveRecord) {
        Region region = baseMapper.selectById(approveRecord.getItemId());
        approveRecord.setItemTableName(SqlHelper.table(Region.class).getTableName());
        approveRecord.setBeforeStatus(region.getStatus());
        if (approveRecord.getType().equals("0")) {
            pass(region, approveRecord);
        } else if (approveRecord.getType().equals("1")) {
            reject(region, approveRecord);
        }
    }

    @Override
    public int updateRegion(Region region) {
        if (StringUtils.isNotEmpty(region.getStatus()) && !region.getStatus().equals("0")) {
            region.setStatus("1");
        }
        return baseMapper.updateById(region);
    }

    @Override
    public RegionVo getRegionByUser() {
        RegionVo regionVo = new RegionVo();
        // 获取当前的用户ID
        String userId = SecurityUtils.getUserId();
        UserRecord userRecord = userRecordMapper.selectOne(new QueryWrapper<UserRecord>()
                .lambda().eq(UserRecord::getUserId, userId));
        if (userRecord == null) {
            List<Section> sectionList = sectionMapper.selectList(new QueryWrapper<Section>()
                    .lambda().eq(Section::getType, "0"));
            regionVo.setSectionList(sectionList);
        } else {
            regionVo = getOnlineDetail(userRecord.getRegionId());
        }
        return regionVo;
    }

    private RegionVo getOnlineDetail(String id) {
        RegionVo regionVo = new RegionVo();
        QueryWrapper<Section> sectionQueryWrapper = new QueryWrapper<>();
        Region region = baseMapper.selectOne(new QueryWrapper<Region>().lambda()
                .eq(Region::getId, id)
                .eq(Region::getStatus, "2"));
        if (region != null) {
            regionVo.setRegion(region);
            sectionQueryWrapper.lambda()
                    .eq(Section::getRegionId, region.getId());
            regionVo.setRegionMap(regionMapMapper.selectOne(new QueryWrapper<RegionMap>().lambda()
                    .eq(RegionMap::getRegionId, region.getId())));
        }
        sectionQueryWrapper.lambda().or()
                .eq(Section::getType, "0")
                .orderByAsc(Section::getType)
                .orderByAsc(Section::getSort);
        regionVo.setSectionList(sectionMapper.selectList(sectionQueryWrapper));
        return regionVo;
    }

    @Override
    public int chooseRegion(String regionId) {
        int result=0;
        if (StringUtils.isNotEmpty(regionId)) {
            if (baseMapper.selectById(regionId) != null) {
                // 获取当前的用户ID
                String userId = SecurityUtils.getUserId();
                UserRecord userRecord = userRecordMapper.selectOne(new QueryWrapper<UserRecord>().lambda()
                        .eq(UserRecord::getUserId, userId));
                if (userRecord != null) {
                    userRecord.setRegionId(regionId);
                    result= userRecordMapper.updateById(userRecord);
                } else {
                    userRecord = new UserRecord();
                    userRecord.setUserId(userId);
                    userRecord.setRegionId(regionId);
                    result= userRecordMapper.insert(userRecord);
                }
                //发送系统通知
                sendMessage(userRecord);
            }
        }
        return result;
    }


    public void sendMessage(UserRecord userRecord) {
        JSONObject message=new JSONObject();
        message.put("userId",userRecord.getUserId());
        message.put("regionId",userRecord.getRegionId());
        message.put("type", NotificationTypeEnum.SYSTEM.getValue());
        message.put("systemType", SystemNotificationTypeEnum.CHOOSE_REGION.getValue());
        rabbitTemplate.convertAndSend(Constants.NOTICE_EXCHANGE, Constants.NOTICE_QUEUE_ROUTING_KEY, message.toString());
    }


    public void reject(Region region, ApproveRecord approveRecord) {
        //地区
        region.setStatus("3");
        baseMapper.updateById(region);
        //审核记录
        approveRecord.setType("1");
        approveRecord.setAfterStatus(region.getStatus());
        approveRecordMapper.insert(approveRecord);
    }


    public void pass(Region region, ApproveRecord approveRecord) {
        //地区
        region.setStatus("2");
        baseMapper.updateById(region);
        //审核记录
        approveRecord.setType("0");
        approveRecord.setAfterStatus(region.getStatus());
        approveRecordMapper.insert(approveRecord);
        //地区审核配置
        if (approveConfigMapper.selectCount(new QueryWrapper<ApproveConfig>()
                .lambda().eq(ApproveConfig::getItemId, region.getId())) == 0) {
            PlatformConfig platformConfig = platformConfigMapper.selectOne(new QueryWrapper<PlatformConfig>().lambda()
                    .eq(PlatformConfig::getKey, "approve_reason")
                    .eq(PlatformConfig::getStatus, "0"));
            ApproveConfig approveConfig = new ApproveConfig();
            approveConfig.setName(region.getName() + "审核配置");
            approveConfig.setSentence(platformConfig.getValueString());
            approveConfig.setItemId(region.getId());
            approveConfig.setMethod("0");
            approveConfigMapper.insert(approveConfig);
        }

    }


    /**
     * 查询地区表列表
     *
     * @param region 地区表
     * @return 地区表
     */
    @OperatorDataScope(fieldName = "userId")
    @DataSource(value = DataSourceType.SLAVE)
    @Override
    public List<Region> selectRegionList(Region region) {
        QueryWrapper<Region> queryWrapper = setQueryWrapper(region);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 设置QueryWrapper条件
     *
     * @param region
     * @return
     */
    public QueryWrapper<Region> setQueryWrapper(Region region) {
        QueryWrapper<Region> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(region.getUserId())) {
            queryWrapper.lambda().like(Region::getUserId, region.getUserId());
        }
        if (StringUtils.isNotEmpty(region.getName())) {
            queryWrapper.lambda().like(Region::getName, region.getName());
        }
        if (StringUtils.isNotEmpty(region.getCode())) {
            queryWrapper.lambda().eq(Region::getCode, region.getCode());
        }
        if (StringUtils.isNotEmpty(region.getAbbreviation())) {
            queryWrapper.lambda().like(Region::getAbbreviation, region.getAbbreviation());
        }
        if (StringUtils.isNotEmpty(region.getType())) {
            queryWrapper.lambda().eq(Region::getType, region.getType());
        }
        if (StringUtils.isNotEmpty(region.getIsPrivate())) {
            queryWrapper.lambda().eq(Region::getIsPrivate, region.getIsPrivate());
        }
        if (StringUtils.isNotEmpty(region.getStatus())) {
            queryWrapper.lambda().eq(Region::getStatus, region.getStatus());
        }

        return queryWrapper;
    }

    /**
     * 批量删除地区表
     *
     * @param ids 需要删除的地区表ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRegionByIds(String[] ids) {
        //删除版块
        sectionMapper.delete(new QueryWrapper<Section>().lambda().in(Section::getRegionId, ids));
        //删除地图
        regionMapMapper.delete(new QueryWrapper<RegionMap>().lambda().in(RegionMap::getRegionId, ids));
        //删除审核配置
        approveConfigMapper.delete(new QueryWrapper<ApproveConfig>().lambda().in(ApproveConfig::getItemId, ids));
        // 获得帖子ID数组
        List<String> postIds = postMapper.selectList(new QueryWrapper<Post>().lambda().in(Post::getRegionId, ids))
                .stream().map(Post::getId).collect(Collectors.toList());
        if (!postIds.isEmpty()) {
            //删除帖子
            postMapper.deleteBatchIds(postIds);
            //删除评论
            commentMapper.delete(new QueryWrapper<Comment>().lambda().in(Comment::getPostId, postIds));
        }
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public boolean addRegion(Region region) {
        //查找固定版块
        List<Section> sectionList = sectionMapper.selectList(new QueryWrapper<Section>().lambda().eq(Section::getType, "0"));
        if (!sectionList.isEmpty()) {
            baseMapper.insert(region);
            return true;
        }
        return false;
    }

}
